<?php

use SinoPHP\BbdBoss\Library\Dnspod;
use Upfor\UpforPHP\Model;

require_once __DIR__ . '/../UpforPHP/bootstrap.php';
require_once __DIR__ . '/../vendor/autoload.php';

$subDomain = 'ip.library.com';
$dnspodObj = new Dnspod();
$params = $argv;

if (isset($params[1]) && 'add' == $params[1]) {
    add($params, $dnspodObj);
}

if (isset($params[1]) && 'del' == $params[1]) {
    del($dnspodObj);
}

/**
 * 记录文件日志
 * 
 * @param mixed array|string $data
 */
function addLog($data, $label = 'error') {
	$logStr = is_array($data) ? json_encode($data) : $data;
	file_put_contents("dnspod_{$label}_log" . date("ymd") . ".log", $logStr, FILE_APPEND);
}

/**
 * Add Records
 * 
 * @param array  $params
 * @param object $dnspodObj
 */
function add($params, $dnspodObj) {
	// 测试记录条数
	$total = @is_numeric($params[2]) ? $params[2] : 5;
	// 分组 每组条数
	$chunk = @is_numeric($params[3]) ? $params[3] : 50;

    // IP 整数 1.1.1.1
    $initIp = 16843009;    
    $dnspodData = [];
    global $subDomain;
    // 所有解析线路
    // $allLines = model("domainDnspodLine")->getList("*", ['status' => 1, 'is_group' => 0], ['id' => 'ASC', 'sort' => 'ASC']);

    $hashKey = 0;
    $doaminPart = explode(".", $subDomain);

    for ($i = 0; $i < $total; $i++) {
    	$hashKey = ceil($i / 50) <= 1 ? '' : ceil($i / 50) - 1; 
        $dnspodData[$i] = [
            'subDomain'  => $doaminPart[0] . '.' .  $doaminPart[1] . $hashKey . '.' . $doaminPart[2],
            'recordType' => "A",
            'recordLine' => '默认',
            'record'     => long2ip($initIp),
            'ttl'        => 300,
        ];

        $initIp ++;
    }

    // 成功数量
    $successNum = 0;

    // 不分组
    if ($total < 50) {
        addRcords($dnspodData, $dnspodObj, $successNum);
    }

    // 分组并发
    if ($total >= 50) {
    	$chunk = $total >= $chunk ? $chunk : $total;
        $newDnspodData = array_chunk($dnspodData, $chunk, true);
        foreach ($newDnspodData as $data) {
            addRcords($data, $dnspodObj, $successNum);
        }
    }

    echo " insert {$successNum} records success\n";
}


/**
 * 添加实体记录
 * 
 * @param array $dnspodData
 */
function addRcords(array $dnspodData, $dnspodObj, &$successNum) {
    $response = $dnspodObj->addRecordMulti($dnspodData);

    $dbData = [];
    $monitorData = [];
    global $subDomain;
    if (!empty($response['success'])) {
        foreach ($response['success'] as $key => $callback) {
            if ($callback['status']['code'] != 1) {
            	$logStr = "\n------------\n {$key} : " . json_encode($callback);
            	addLog($logStr);
                continue;
            }

            $dbData[] = [
                'dnspod_id' => $callback['record']['id'],
                'record_type' => $dnspodData[$key]['recordType'],
                'record_line' => $dnspodData[$key]['recordLine'],
                'record' => $dnspodData[$key]['record'],
                'create_time' => time()
            ];

            $monitorDataTemp = [
            	'recordId' => $callback['record']['id'],
	            'recordHost' => $subDomain . '.bbdcdn.com',
	            'bakIp' => 'pass'
        	];
            if (!empty($callback['monitor']['id'])) {
            	$monitorData['edit'][$key] = array_merge($monitorDataTemp, ['monitorId' => $callback['monitor']['id']]);
            } else {
            	$monitorData['add'][$key] = $monitorDataTemp;
            }

            $successNum ++;
        }
    }

    if (empty($dbData)) {
    	return;
    }
    model('tempDnspod')->insert($dbData);

    // 添加、修噶监控
    if (!empty($monitorData)) {
    	addMonitor($dnspodObj, $monitorData);
    }
}

/**
 * 添加、修噶监控
 * 
 * @param object $dnspodObj
 * @param array $monitorData
 */
function addMonitor($dnspodObj, $monitorData) {
	$success = [];

	// 修改监控
	$editResponse['success'] = [];
	if (!empty($monitorData['edit'])) {
		$editResponse = $dnspodObj->editMonitorMulti($monitorData['edit']);
	}
	// 添加监控
	$addResponse['success'] = [];
	if (!empty($monitorData['add'])) {
		$addResponse = $dnspodObj->addMonitorMulti($monitorData['add']);
	}

	$success = ($editResponse['success'] + $addResponse['success']);
	if (empty($success)) {
		return;
	}
	
	$updateData = [];
	foreach ($success as $key => $callback) {
		if ($callback['status']['code'] != 1) {
			addLog($callback);
			continue;
		}

		$updateData[] = [
			'dnspod_id' => !empty($monitorData['edit'][$key]['recordId']) ? $monitorData['edit'][$key]['recordId'] : $monitorData['add'][$key]['recordId'],
			'monitor_id' => !empty($callback['monitor']['monitor_id']) ? $callback['monitor']['monitor_id'] : $monitorData['edit'][$key]['monitorId']
		]; 
	}

	if (!empty($updateData)) {
		$sql = model("tempDnspod")->insert($updateData, true);
	}
}

/**
 * 删除记录
 * 
 * @param  object $dnspodObj
 * @return none
 */
function del($dnspodObj) {
	$dnspodList = model("tempDnspod")->getList();
	$totalNum = count($dnspodList);
	$chunk = 50;

	if (empty($dnspodList)) {
	    echo "there no records to delete";
	    die;
	}

	$deleteNum = 0;
	if ($totalNum > 50) {
		$newDnspodList = array_chunk($dnspodList, $chunk, true);
		foreach ($newDnspodList as $data) {
			delRecords($data, $dnspodObj, $deleteNum);
		}
	} else {
		delRecords($dnspodList, $dnspodObj, $deleteNum);
	}

	echo "there are totally {$totalNum} records, delete {$deleteNum} records success\n";	
}

/**
 * 删除记录实体
 * 
 * @param  array $dnspodList 
 * @param  object $dnspodObj  
 * @param  integer &$deleteNum 
 * @return none             
 */
function delRecords($dnspodList, $dnspodObj, &$deleteNum) {
	$dnspodData = [];
	foreach ($dnspodList as $key => $val) {
	    $dnspodData[$val['id']] = [
	        'recordId' => $val['dnspod_id'],
	    ];
	}

	$response = $dnspodObj->deleteRecordMulti($dnspodData);

	$dbData = [];
	if (!empty($response['success'])) {
	    foreach ($response['success'] as $key => $callback) {
	        if ($callback['status']['code'] != 1) {
	            continue;
	        }

	        $dbData[] = $key; 
	        $deleteNum ++;
	    }
	}

	model('tempDnspod')->delete(['id' => $dbData]);
}
